//index.js
//获取应用实例
const messageService = require('../../services/messageService');
var app = getApp()
Page({
  data: {
    msg_list: {},
    page: 1,
    totalPage: 0,
    datalist: [],
    error: false,
    errorMsg: ''
  },
  //事件处理函数
  bindDetail: function(event) {
    var id = event.currentTarget.dataset.id;
    var status = event.currentTarget.dataset.status;
    wx.navigateTo({
      url: '../messageDetail/messageDetail?msg_id=' + id + '&status=' + status
    })
  },

  onPullDownRefresh: function(){
    var that = this;
    if((this.data.page + 1)>this.data.totalPage) {
      this.setData({
        error:true,
        errorMsg: '没有更多数据'
      });
      setTimeout(function(){
        that.setData({
          error:false
        });
      },2000);
      wx.stopPullDownRefresh();
      return;
    }
    this.setData({
      page: this.data.page + 1
    })
    this._getMsgList(this.data.page);
  },

  bindScanCode: function() {
    app.bindScanCode();
  },
  updateMsgState: function(msgId) {
      var msgList = this.data.msg_list.data;
      if(msgList && msgList.length > 0) {
        for(var i = 0 ;i<msgList.length; i++){
          if(msgList[i].msg_id == msgId) {
            msgList[i].status = 1;
            this.setData({
              msg_list: this.data.msg_list
            });
            break;
          }
        }
      }
  },

  _getMsgList: function(page){
    var that = this;
    var user = wx.getStorageSync('user');
    if(user) {
      wx.showLoading({
        title: '加载数据...'
      });
      messageService.getMsgList(user.openid,page).then((data) => {
          var data = data.data;
          var msgList = data.msg_list;
          var totalPage = Math.ceil(msgList.total/msgList.per_page);
          that.data.datalist = that.data.datalist.concat(msgList.data);
          msgList.data = that.data.datalist; 
          that.setData({
            msg_list: msgList,
            totalPage: totalPage
          });
           wx.hideLoading();
        }, (error) => {
        });
      }
  },
  onLoad: function () {
    var user = wx.getStorageSync('user');
    if(user) {
      this._getMsgList(1);
    } else {
      this.setData({
        error:true,
        errorMsg: '用户未同意授权！'
      });
      setTimeout(function(){
        that.setData({
          error:false
        });
      },2000);
    }
    app.editTabBar();//添加tabBar数据  
    var that = this;
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      //更新数据
      that.setData({
        userInfo:userInfo
      })
    })
  }
})
